package com.argrace.smart.activity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.business.alink.ALinkBusinessEx;
import com.aliyun.alink.business.devicecenter.api.add.DeviceInfo;
import com.aliyun.alink.sdk.net.anet.api.AError;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryRequest;
import com.aliyun.alink.sdk.net.anet.api.transitorynet.TransitoryResponse;
import com.argrace.smart.ArgraceApplication;
import com.argrace.smart.R;
import com.argrace.smart.base.ActivityManager;
import com.argrace.smart.base.BaseActivity;
import com.argrace.smart.thread.MyRecieveUdpThread;
import com.argrace.smart.thread.MySendUdpThread;
import com.argrace.smart.util.AlinkHttpUtil;
import com.argrace.smart.util.Logg;

import org.apache.commons.codec.digest.DigestUtils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.HashMap;

/**
 * Created by argrace_dev_1 on 2018/1/31.
 * 绑定网关界面
 */

public class BindDeviceActivity extends BaseActivity {
    private TextView getuuid;
    private TextView bind;
    Thread thread_recieve;
    MySendUdpThread thread_send;
    private String add = "224.0.0.1";
    private int port = 5355;
    private int port_send = 5354;
    private String mac, sn, model;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_binddevice);
        init();
    }

    private void init() {
        mac = getIntent().getStringExtra("mac");
        sn = getIntent().getStringExtra("sn");
        model = getIntent().getStringExtra("model");
        Logg.i("info", "BindDeviceActivity.init(),mac = " + mac + "---sn = " + sn + "---model = " + model);
        setTitle(true, false, "绑定选中网关");
        setView();
        startRecieveAndSendUdp();
    }

    //开始监听UDP组播，并发送UDP消息
    @SuppressLint("WrongConstant")
    private void startRecieveAndSendUdp() {
        MyRecieveUdpThread runnable_recieve = new MyRecieveUdpThread(add, port, new MyRecieveUdpThread.RecieveUdpThreadCallBack() {
            //收到组播后的回调
            @Override
            public void callBack(String msg) {
                Log.i("info", "BindDeviceActivity中收到UDP组播回调,msg = " + msg);
                getuuid.setTextColor(Color.BLACK);
                JSONObject obj = JSON.parseObject(msg);
                String uuid = null;
                if (obj != null) {

                    uuid = obj.getString("Uuid");
                }
                bindDevice(uuid);
            }
        });
        //监听组播开启
        thread_recieve = new Thread(runnable_recieve, "recieve");
        if (thread_recieve.isAlive()) {
            Toast.makeText(BindDeviceActivity.this, "监听已启动，请勿重复", 3000).show();
        } else {
            thread_recieve.start();
        }
        //发送组播
        String mac_md5 = DigestUtils.md5Hex(sn);
        String sendMsg = "{\"Command\":\"Get\",\"PassWord\":\"" + mac_md5 + "\"}";
        Logg.i("info", "udp发送的数据是" + sendMsg);
        thread_send = new MySendUdpThread(add, port_send, sendMsg);
        thread_send.start();
    }

    private void setView() {
        getuuid = (TextView) findViewById(R.id.activity_binddevice_getuuid);
        bind = (TextView) findViewById(R.id.activity_binddevice_bind);
    }

    private void bindDevice(@NonNull String uuid) {
        Logg.i("info", "BindDeviceActivity.bindDevice()start,uuid=" + uuid);
        String method = "mtop.openalink.app.core.user.binddevice";
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("uuid", uuid);
        AlinkHttpUtil.AlinkHttpRequest(method, hashMap, new ALinkBusinessEx.IListener() {
            @Override
            public void onSuccess(TransitoryRequest transitoryRequest, TransitoryResponse transitoryResponse) {
                Logg.i("info", "绑定设备成功" + transitoryResponse.data);
                toastActBtm("绑定设备成功");
                bind.setTextColor(Color.BLACK);
                ArgraceApplication.is_RefreshWangGuanList = true;
                finish();
                try {
                    ActivityManager.getActivity(SearchDeviceActivity.class.getName()).finish();
                } catch (Exception e) {

                }

            }

            @Override
            public void onFailed(TransitoryRequest transitoryRequest, AError aError) {
                Logg.i("info", "绑定设备失败" + aError.getMsg() + aError.getCode() + "----" + aError.getSubCode());
                toastActBtm("绑定设备失败");
                getuuid.setTextColor(Color.rgb(240, 240, 240));

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private static String getMD5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
            System.out.println("MD5(" + sourceStr + ",32) = " + result);
            return result;
        } catch (Exception e) {
            return null;
        }
    }
}
